#! /usr/bin/python
# -*- coding:  utf-8 -*-
#
# accoufer : cgi script for creating/editing an offer
# 
# Copyright S.Keim 2011
# Available under the MIT licence see the COPYING file

import accoufer
import shelve
import cgi 

def run():
    class param:
        svalue = 0
        min_svalue=0
        tx = 0
    # logged user
    login, user = accoufer.userCookie()

    # extract parameters
    form = cgi.FieldStorage()
    try:
        param.ref = form["ref"].value
    except KeyError:
        return fatal_error("Invalid request")
    
    #todo extract oid to edit existing offer
    if "svalue" not in form:
        print accoufer.HTML%("Create new offer", FORM%param.__dict__)
        return 
    try:
        param.svalue = int(form["svalue"].value)
        param.min_svalue  = int(form["min_svalue"].value)
        param.tx = float(form["tx"].value)
    except (KeyError, ValueError):
        return error("Invalid parameters", param)

    #  check min<max
    if param.svalue < param.min_svalue:
        param.svalue , param.min_svalue = param.min_svalue, param.svalue 
        return error("Reversed min-max parameters", param)
    #check user
    if user[accoufer.USER_CREDITS]<param.svalue:
        return error("Credits overflow", param)

    # check if user has an offer for this service, then edit it
    offers = shelve.open(accoufer.offerpath(param.ref), 'w') # Todo file not found error
    for client,oref in user[accoufer.USER_OFFERS]:
        if client==param.ref:
            break
    else:
        try:
            #create  a new offer
            ocount = offers[accoufer.COUNT_KEY]+1
            offers[accoufer.COUNT_KEY] = ocount
            oref = str(ocount)
            #register in user db
            user[accoufer.USER_OFFERS].append( (param.ref, oref) )
            users = shelve.open(accoufer.USER_PATH)
            users[login] = user             
        except KeyError: 
            return fatal_error("Invalid request")    
    offers[oref] = (oref, param.svalue, param.min_svalue, param.tx, login)   

    # output message
    msg =  SUCCES
    print accoufer.HTML%("Offer created", msg)

def fatal_error(txt):
    print accoufer.HTML%("Fatal error", txt)
        
def error(txt, param):   
    param.error=txt
    msg = ERROR%param.__dict__
    print accoufer.HTML%("Error", msg)

SUCCES = """<h1>New offer</h1>Offer successfully created.<p/> <a href="./index.html">Start</a>"""

IN_FORM = """<form method=post action="./xeditoffer">
Total value proposed: <input name="svalue" value="%(svalue)s"/> credits on this site<br/>
Min value by transaction: <input name="min_svalue" value="%(min_svalue)s"/> credits on this site<br/>
1 credit on this site must be exchanged for <input name="tx" value="%(tx)s"/> credits on remote service<br/>
<input type="hidden" name="ref" value="%(ref)s"/><br/>
<input type="submit" value="Run"/></form><p/>
<hr/><a href="./index.html">Start</a> 
"""
FORM = "<h1>Create new offer</h1>"+IN_FORM

ERROR = "<h1>Error</h1><b>%(error)s</b><p/>"+IN_FORM


if __name__=="__main__":
    run()

